<template>
    <el-row class="border-radius">
        <el-form :inline="true" :model="queryForm" class="query-form" v-permission="['user.list']" @submit.enter.prevent>
            <el-form-item :label="$t('data.search.label.keyword')">
                <el-input v-model="queryForm.name" :placeholder="$t('data.search.placeholder.keyword')"></el-input>
            </el-form-item>
            <el-form-item :label="$t('user.search.organizationName')">
                <el-select v-model="queryForm.organization" filterable  class="table-item">                    
                    <el-option
                    v-for="item in organizationSearchOptions"
                    :key="item.organizationId"
                    :label="item.organizationName"
                    :value="item.organizationId"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="queryData">{{$t('data.button.search')}}</el-button>
            </el-form-item>
        </el-form>
    </el-row>
    <div class="border-radius mt4">
        <el-row class="operate" v-permission="['user.add','user.del','user.resetpwd']">
            <el-button type="success" @click="showAddDialog" v-permission="['user.add']">{{$t('data.button.add')}}</el-button>
            <el-button type="danger" @click="deleteConfirm" :disabled="selectData.length==0" v-permission="['user.del']">{{$t('data.button.delete')}}</el-button>
            <el-button type="primary" @click="resetPwdConfirm" :disabled="selectData.length==0" v-permission="['user.resetpwd']">{{$t('user.resetPwdButtonText')}}</el-button>
            <el-alert :title="$t('data.tip.selected',{count:selectData.length})" type="warning" show-icon :closable='false' v-if="selectData.length>0 && $hasPermission(['user.del','user.resetpwd'])"></el-alert>
        </el-row>
    
        <el-table :data="tableData" border @selection-change="handleSelectionChange" v-loading="loading" v-permission="['user.list']">
            <el-table-column type="selection" width="55" v-permission="['user.del','user.resetpwd']"/>
            <el-table-column prop="userName" :label="$t('user.userName')" />
            <el-table-column prop="userAccount" :label="$t('user.userAccount')" />
            <el-table-column prop="organizationName" :label="$t('user.organizationName')" />
            <el-table-column prop="phone" :label="$t('user.phone')" />
            <el-table-column prop="mail" :label="$t('user.mail')" />
            <el-table-column fixed="right" :label="$t('data.column.operate')" v-permission="['user.edit','user.assignrole']">
                <template #default="scope">
                    <el-button type="text" @click="showEditDialog(scope.row)" v-permission="['user.edit']">{{$t('data.button.edit')}}</el-button>
                    <el-button type="text" @click="showUserRoleDialog(scope.row)" v-permission="['user.assignrole']">{{$t('user.assignRoleButtonText')}}</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row v-permission="['user.list']">
            <el-pagination
            v-model:currentPage="queryForm.pageIndex"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 50, 100, 500]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItemCount"
            class="fr"
            >
            </el-pagination>
        </el-row>
    </div>
    <add-user :form="dialogForm" :organizationOptions="organizationTreeOptions" :add="isAddDialog" :visible="showDialog" @submit="addOrUpdateUser" @close="closeAddDialog"/>
    <reset-pwd :visible="showResetPwdDialog" @submit="submitResetPwd" @close="closeResetPwdDialog"/>
    <user-role :userId='editUserId' :visible="showAssignRoleDialog" @submit="submitUserRole" @close="closeUserRoleDialog"/>
</template>
<script>
import userApi from '@/api/user'
import orgApi from '@/api/organization'
import AddUser from './AddUser.vue'
import ResetPwd from './ResetPwd.vue'
import UserRoleList from './UserRoleList.vue'
export default{
    components:{
        AddUser,
        ResetPwd,
        'UserRole':UserRoleList
    },
    data(){
        return {
            queryForm:{
                pageIndex:1,
                pageSize:10,
            },
            totalItemCount:0,
            tableData:[],
            selectData:[],
            showDialog:false,
            isAddDialog:false,
            dialogForm:{},
            loading:false,
            showResetPwdDialog:false,
            showAssignRoleDialog:false,
            editUserId:null,
            organizationTreeOptions:[],
            organizationSearchOptions:[]
        }
    },
    mounted(){
        this.queryOrganization()
        this.getTableList()
    },
    watch:{
        'queryForm.pageIndex':function(){
            this.getTableList();
        },
        'queryForm.pageSize':function(){
            if(this.queryForm.pageIndex==1){
                this.getTableList();
            }
            else{
                this.queryForm.pageIndex=1
            }
        }
    },
    methods:{
        queryData(){
            this.queryForm.pageIndex=1;
            this.getTableList();
        },
        handleSelectionChange(data){
            console.log('handleSelectionChange',data)
            this.selectData=data;
        },
        queryOrganization(){
            orgApi.queryOrganizations().then(d=>{
                if(!!d && d.code=='200'){
                    this.organizationSearchOptions=[{organizationId:'',organizationName:''}].concat(d.data || [])
                }
            })
        },
        getTableList(){
            console.log('queryTable',this.queryForm)
            this.loading=true
            userApi.userPager(this.queryForm).then(d=>{
                this.loading=false
                console.log(d)
                if(!!d && d.code=='200'){
                    this.totalItemCount=d.data.totalItemCount;
                    this.tableData=d.data.dataList || []
                }
            }).catch(()=>this.loading=false)
        },
        showUserRoleDialog(row){
          this.editUserId=row.userId
          this.showAssignRoleDialog=true
        },
        async showAddDialog(){
            await this.getOrgTree()
            this.showDialog=true;
            this.isAddDialog=true;
            this.dialogForm={}
        },
        closeAddDialog(){
            this.showDialog=false;
            this.dialogForm={}
        },
        addOrUpdateUser(form){            
            if(this.isAddDialog){
                userApi.addUser(form).then(d=>{
                    if(!!d && d.code=='200'){
                        this.$message({
                            showClose: true,
                            message: this.$t('data.result.addSuccess'),
                            type: 'success',
                        })
                        this.closeAddDialog();
                        this.getTableList();
                    }
                })
            }
            else{
                userApi.updateUser(form).then(d=>{
                    if(!!d && d.code=='200'){
                        this.$message({
                            showClose: true,
                            message: this.$t('data.result.updateSuccess'),
                            type: 'success',
                        })
                        this.closeAddDialog();
                        this.getTableList();
                    }
                })
            }
        },
       getOrgTree(){
             return orgApi.getOrganizationTree(this.queryForm).then(d=>{
                this.loading=false
                console.log(d)
                if(!!d && d.code=='200'){
                    this.organizationTreeOptions=d.data || []
                    return Promise.resolve()
                }
                return Promise.reject()
            }).catch(()=>Promise.reject())
        },
         
        async showEditDialog(row){
            await this.getOrgTree()
            this.dialogForm={}
            userApi.getUser(row.userId).then(d=>{
                if(!!d && d.code=='200'){
                    this.dialogForm=d.data || {}
                    this.isAddDialog=false;
                    this.showDialog=true;                    
                }
                else{
                    this.$message({
                        showClose: true,
                        message: this.$t('data.list.error'),
                        type: 'error',
                    })
                }
            })
        },
        deleteConfirm(){
            this.$messageBox.confirm(this.$t('data.confirm.delete'),this.$t('data.confirm.title'),{
                type: 'warning',
            })
            .then(() => {
                userApi.deleteUsers(this.selectData.map(a=>a.userId)).then(d=>{
                    if(!!d && d.code=='200'){
                        this.$message({
                            showClose: true,
                            message: this.$t('data.result.deleteSuccess'),
                            type: 'success',
                        })
                        this.queryData();
                    }
                })
            })            
        },
        resetPwdConfirm(){
          this.showResetPwdDialog=true
        },
        submitResetPwd(newPassword){
          userApi.resetPwd({userIds:this.selectData.map(a=>a.userId),newPassword:newPassword})
          .then(d=>{
              if(!!d && d.code=='200'){
                  this.$message({
                      showClose: true,
                      message: this.$t('user.resetPwdSuccess'),
                      type: 'success',
                  })
                  this.closeResetPwdDialog()
                  this.getTableList();
              }
          })
        },
        closeResetPwdDialog(){
            this.showResetPwdDialog=false;
        },
        closeUserRoleDialog(){
            this.showAssignRoleDialog=false;
        },
        submitUserRole(roleIds){
          userApi.updateUserRoles(this.editUserId,roleIds)
          .then(d=>{
              if(!!d && d.code=='200'){
                  this.$message({
                      showClose: true,
                      message: this.$t('user.assignRoleSuccess'),
                      type: 'success',
                  })
                  this.closeUserRoleDialog()
                  this.getTableList();
              }
          })
        },
    }
}
</script>
